# coding: UTF-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np


class Config(object):
    """配置参数"""
    def __init__(self, dataset, embedding):
        self.model_name = 'FastText'
        self.train_path = '/data/sfq/oco/train.csv'                                   # 训练集
        self.test_path = '/data/sfq/oco/test_new.csv'                                 # 测试集
        self.stop_words = '/data/sfq/oco/stopwords.txt' 
        self.save_path = '/data/sfq/oco/model.pt'                                # 模型训练结果
        self.log_path = '/data/sfq/oco/'
        self.embedding_pretrained = torch.tensor(
            np.load(dataset + '/data/' + embedding)["embeddings"].astype('float32'))\
            if embedding != 'random' else None                                       # 预训练词向量
        self.device = torch.device('cuda:7' if torch.cuda.is_available() else 'cpu')   # 设备

        self.dropout = 0.5                                              # 随机失活
        self.dropout_lstm = 0.5
        self.require_improvement = 1000                                 # 若超过1000batch效果还没提升，则提前结束训练
        self.num_classes = 2                                            # 类别数
        self.n_vocab = 0                                                # 词表大小，在运行时赋值
        self.num_epochs = 20                                            # epoch数
        self.batch_size = 256                                           # mini-batch大小
        self.pad_size = 32                                              # 每句话处理成的长度(短填长切)
        self.learning_rate = 1e-3                                       # 学习率
        self.embed = self.embedding_pretrained.size(1)\
            if self.embedding_pretrained is not None else 1024          # 字向量维度
        self.hidden_size = 768                                          # 隐藏层大小
        self.n_gram_vocab = 250499                                      # ngram 词表大小 250499（效果更好）
        self.num_heads = 8
        self.num_layers = 4
        self.is_bidirectional = False
        self.gpu_id = 2
        self.fold = 5
        self.is_fold = False



def _weights_init(m):
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
    if isinstance(m, nn.Conv1d):
        nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
    elif isinstance(m, nn.BatchNorm1d):
        nn.init.constant_(m.weight, 1)
        nn.init.constant_(m.bias, 0)

class MLP(nn.Module):
    def __init__(self, in_features, out_features, hidden, bias, dropout):
        super(MLP, self).__init__()
        if hidden:
            hidden_dim = 2*(in_features+out_features) // 3
            self.mlp = nn.Sequential(
                nn.Linear(in_features, hidden_dim, bias=bias),
                nn.ReLU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_dim, hidden_dim, bias=bias),
                nn.ReLU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_dim, out_features, bias=bias),
            )
        else:
            self.mlp = nn.Linear(in_features, out_features, bias=bias)

        self.apply(_weights_init)

    def forward(self, x):
        return self.mlp(x)
    

class LinearHead(nn.Module):
    def __init__(self, in_features, class_num, hidden, bias, dropout):
        super(LinearHead, self).__init__()
        self.head = MLP(in_features=in_features, out_features=class_num, hidden=hidden, bias=bias, dropout=dropout)

    def forward(self, x):
        if len(x.shape) == 3:
            bsz, _, _ = x.shape
            x = x.reshape(bsz, -1)
        x = self.head(x)

        return x

class Model(nn.Module):
    def __init__(self, config):
        super(Model, self).__init__()
        if config.embedding_pretrained is not None:
            self.embedding = nn.Embedding.from_pretrained(config.embedding_pretrained, freeze=False)
        else:
            self.embedding = nn.Embedding(config.n_vocab, config.embed, padding_idx=config.n_vocab - 1)
        self.embedding_ngram2 = nn.Embedding(config.n_gram_vocab, config.embed)
        self.embedding_ngram3 = nn.Embedding(config.n_gram_vocab, config.embed)
        self.fc_keywords = nn.Linear(1, config.embed)
        
        # if config.is_bidirectional:
        #     self.lstm1 = nn.LSTM(config.embed, (int)(config.embed/2), config.num_layers,
        #                     bidirectional=config.is_bidirectional, batch_first=True, dropout=config.dropout_lstm)
        # else:
        #     self.lstm1 = nn.LSTM(config.embed, config.embed, config.num_layers,
        #                     bidirectional=config.is_bidirectional, batch_first=True, dropout=config.dropout_lstm)
        # self.lstm2 = nn.LSTM(config.embed, config.embed, config.num_layers,
        #                     bidirectional=False, batch_first=True, dropout=config.dropout_lstm)
        # self.lstm3 = nn.LSTM(config.embed, config.embed, config.num_layers,
        #                     bidirectional=False, batch_first=True, dropout=config.dropout_lstm)

        
        self.dropout = nn.Dropout(config.dropout)
        self.fc1 = nn.Linear(config.embed * 4, config.hidden_size)
        self.fc2 = LinearHead(config.hidden_size, config.num_classes, hidden=True,
                                    bias=True, dropout=0.2)

    def forward(self, x):

        out_word = self.embedding(x[0])
        # out_word, _ = self.lstm1(out_word)
        out_bigram = self.embedding_ngram2(x[2])
        # out_bigram, _ = self.lstm2(out_bigram)
        out_trigram = self.embedding_ngram3(x[3])
        # out_trigram, _  = self.lstm3(out_trigram)
        out_keywords = self.fc_keywords(x[4].float().unsqueeze(1).unsqueeze(1))
        out_keywords = out_keywords.expand(-1, x[0].size(1), -1)  # 扩展维度
        out = torch.cat((out_word, out_bigram, out_trigram, out_keywords), -1)

        out = out.mean(dim=1)
        out = self.dropout(out)
        out = self.fc1(out)
        out = F.relu(out)
        out = self.fc2(out)
        return out